import { useSyncExternalStore } from 'react'

// React applications are built from components. Components are built from
// Hooks, whether built-in or custom. You’ll likely often use custom Hooks
// created by others, but occasionally you might write one yourself!

// You must follow these naming conventions:
//   - React component names must start with a capital letter, like `StatusBar`
//     and `SaveButton`. React components also need to return something that
//     React knows how to display, like a piece of JSX.
//   - Hook names must start with `use` followed by a capital letter, like
//     `useState` (built-in) or `useOnlineStatus` (custom, like earlier on the
//     page). Hooks may return arbitrary values.

function subscribe(callback) {
  window.addEventListener('online', callback)
  window.addEventListener('offline', callback)

  return () => {
    window.removeEventListener('online', callback)
    window.removeEventListener('offline', callback)
  }
}

export default function useOnlineStatus() {
  return useSyncExternalStore(
    subscribe,
    () => navigator.onLine,
    () => true
  )
}
